/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @TaskTextView.java  2014年9月16日 下午4:58:08 - Guzhu
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.view;

import java.math.BigDecimal;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.android.scsd.tiango.R;
import com.android.tiango.baba.BaBaseApplication;
import com.android.tiango.baba.entity.TaskModel;
import com.android.tiango.baba.view.TaskScrollView.ScrollListener;

public class TaskTextView extends TextView implements ScrollListener, OnClickListener {
	// view 自身高度
	private int mHeight;
	// 递减/递增 的变量值
	private double mRate;
	// view 设置的值
	private int mValue;
	// 当前显示的值
	private int mCurValue;
	// 当前变化后最终状态的目标值
	private int mGalValue;
	// 控制加减法
	private int rate = 1;
	// 当前变化状态(增/减/不变)
	private int mState = 0;
	private boolean refreshing;
	private static final int REFRESH = 1;
	private static final int SCROLL = 2;
	// 偏移量 主要用来进行校正距离。
	private static final int OFFSET = 20;
	// view 距离scrollView最顶端高度
	private int locHeight = 0;
	private Paint mR_Paint_3;
	private Paint mR_Paint_2;
	private Paint mR_Paint_1;
	private int barColor;
	private RectF rectBg;
	private int speedSize = 10;
	private int barSize = 5;
	private int mXqSize = 10;
	private float TotalSize = 100;
	private float mAngle = 360 / TotalSize;
	private int arcRadius;
	private Point mCenterPoint;
	private int mBgColor;
	private OnclickListener mListener;

	private LinearGradient mLinearGradient;
	private Matrix mGradientMatrix;
	private Paint mPaint;
	private int mViewWidth = 0;
	private int mTranslate = 0;
	private TaskModel taskModel;

	private boolean mAnimating = true;
	private StaticLayout mLineLayout;
	private TextPaint mT_Paint_Line;
	public static final int TASK_FINISH = 0;
	public static final int TASK_NOT_START = 1;
	public static final int TASK_START = 2;
	private int mNow_Type;
	private float mDefaultFontSize;
	private float mTaskFontSize;

	public TaskModel getTaskModel() {
		return taskModel;
	}

	public void setTaskModel(TaskModel taskModel) {
		int value = (int) (taskModel.getFinishNumber() / (float) taskModel.getTaskNumber() * 100);
		if (value > 100) {
			value = 100;
		}
		setValue(value);
		this.taskModel = taskModel;
		Message msg = mHandler.obtainMessage();
		msg.what = SCROLL;
		mHandler.sendMessage(msg);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case REFRESH:
				if (rate * mCurValue < mGalValue) {
					refreshing = true;
					// setText(fnum.format(mCurValue));
					if (mGalValue != 0 && mGalValue != 100) {
						setText(mCurValue + "%");
					}
					mCurValue += mRate * rate;
					mHandler.sendEmptyMessageDelayed(REFRESH, 50);
				} else {
					refreshing = false;
					mCurValue = mGalValue;
					if (mGalValue != 0 && mGalValue != 100) {
						setText(mCurValue + "%");
					}
					// setText(mGalValue + "%");
				}
				break;

			case SCROLL:
				doScroll(msg.arg1, msg.arg2);
				break;

			default:
				break;
			}
		};
	};

	public TaskTextView(Context context) {
		this(context, null);
	}

	public TaskTextView(Context context, AttributeSet set) {
		this(context, set, 0);
	}

	public TaskTextView(Context context, AttributeSet set, int defStyle) {
		super(context, set, defStyle);
		TypedArray mTypedArray = context.obtainStyledAttributes(set, R.styleable.MyTaskTextView);

		// 获取自定义属性和默认值
		mDefaultFontSize = mTypedArray.getDimension(R.styleable.MyTaskTextView_textSize, 25);
		mTaskFontSize = mDefaultFontSize / 2;
		mTypedArray.recycle();
		initView();
	}

	private void initView() {
		setGravity(Gravity.CENTER);
		setTextColor(Color.rgb(255, 255, 255));
		setOnClickListener(this);
	}

	public void setLocHeight(int height) {
		locHeight = height;
	}

	public void setValue(int value) {
		mCurValue = 0;
		if (value == 0) {
			mNow_Type = TASK_NOT_START;
			mGalValue = isShown() ? value : 0;
		} else if (value == 100) {
			mNow_Type = TASK_FINISH;
			mGalValue = isShown() ? value : 1;
		} else {
			mNow_Type = TASK_NOT_START;
			mGalValue = isShown() ? value : 1;
		}
		mValue = value;
		mRate = (double) (mValue / 20);
		BigDecimal b = new BigDecimal(mRate);
		mRate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		arcRadius = (getWidth() - 2 * speedSize) / 2;
		if (mR_Paint_3 == null) {
			mR_Paint_3 = new Paint();
			mR_Paint_3.setColor(barColor);
			mR_Paint_3.setStrokeWidth(barSize);
			mR_Paint_3.setAntiAlias(true);
			mR_Paint_3.setStyle(Paint.Style.STROKE);
		}
		if (mR_Paint_2 == null) {
			mR_Paint_2 = new Paint();
			mR_Paint_2.setColor(barColor);
			mR_Paint_2.setStyle(Paint.Style.FILL);
			mR_Paint_2.setAntiAlias(true);
		}
		if (null == mCenterPoint) {
			mCenterPoint = new Point(getWidth() / 2, (getWidth() / 2));
		}
		if (barColor == 0) {
			barColor = Color.argb(255, 0, 0, 0);
		} else {
			if (mViewWidth > 0) {
				int r = Color.red(barColor);
				int g = Color.green(barColor);
				int b = Color.blue(barColor);
				int color = Color.argb(33, r, g, b);
				int color2 = Color.argb(88, r, g, b);
				mBgColor = color;
				mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0, new int[] { color2,
						barColor, color2 }, new float[] { 0, 0.5f, 1 }, Shader.TileMode.CLAMP);
				mR_Paint_3.setShader(mLinearGradient);
				mR_Paint_3.setAntiAlias(true);
				mGradientMatrix = new Matrix();
			}
		}
		if (mR_Paint_1 == null) {
			mR_Paint_1 = new Paint(); // 初始化画笔，为后面阴影效果使用。
			mR_Paint_1.setColor(mBgColor);
			mR_Paint_1.setStrokeWidth(barSize);
			mR_Paint_1.setAntiAlias(true);
			mR_Paint_1.setStyle(Paint.Style.STROKE);
		}
		mR_Paint_1.setColor(mBgColor);
		mR_Paint_2.setColor(barColor);
		mR_Paint_3.setColor(barColor);
		if (null == rectBg) {
			rectBg = new RectF(speedSize, speedSize, getWidth() - speedSize, getWidth() - speedSize);
		}
		if (mAnimating && mGradientMatrix != null) {
			mTranslate += mViewWidth / 10;
			if (mTranslate > 2 * mViewWidth) {
				mTranslate = -mViewWidth;
			}
			mGradientMatrix.setTranslate(mTranslate, 0);
			mLinearGradient.setLocalMatrix(mGradientMatrix);
			postInvalidateDelayed(100);
		}

		if (mT_Paint_Line == null) {
			mT_Paint_Line = new TextPaint();
			mT_Paint_Line.setColor(Color.rgb(255, 255, 255));
			mT_Paint_Line.setTextSize(14);
			mT_Paint_Line.setAntiAlias(true);
		}

		if (mGalValue != 0 && mGalValue != 100) {
			mLineLayout = new StaticLayout(mCurValue + "", mT_Paint_Line, 2 * mXqSize,
					Layout.Alignment.ALIGN_CENTER, 1f, -4f, false);
		}
		float yAngle = mCurValue * mAngle;
		if (mGalValue != 0) {
			canvas.drawArc(rectBg, -90, yAngle, false, mR_Paint_3);
		}
		Point point = getRadPoint(mCenterPoint, arcRadius, yAngle - 90);
		if (mGalValue != 0 && mGalValue != 100) {
			mNow_Type = TASK_START;
			canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, arcRadius, mR_Paint_1);
			canvas.drawCircle((float) point.x, point.y, mXqSize, mR_Paint_2);// 小圆
		} else if (mGalValue == 0) {
			canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, arcRadius, mR_Paint_1);
			mNow_Type = TASK_NOT_START;
		} else if (mGalValue == 100) {
			mNow_Type = TASK_FINISH;
		}
		super.onDraw(canvas);
		if (mGalValue != 0 && mGalValue != 100) {
			canvas.translate((float) point.x - mXqSize, point.y - mXqSize);
			setTextSize(mDefaultFontSize);
			mLineLayout.draw(canvas);
		} else if (mGalValue == 0) {
			setTextSize(mTaskFontSize);
			setText("启动任务");
		} else if (mGalValue == 100) {
			setTextSize(mTaskFontSize);
			setText("领取奖品");
		}
	}

	@Override
	public void onScrollChanged(int state, int scroll) {
		Message msg = mHandler.obtainMessage();
		msg.what = SCROLL;
		msg.arg1 = state;
		msg.arg2 = scroll;
		mHandler.sendMessage(msg);
	}

	private void doScroll(int state, int scroll) {
		if (mState == state && refreshing)
			return;

		mState = state;
		// if (doMinus(scroll)) {
		// // rate = -1;
		// // mGalValue = 0;
		// } else
		// if (doPlus(scroll)) {
		rate = 1;
		mGalValue = mValue;
		// }
		mHandler.sendEmptyMessage(REFRESH);
	}

	private boolean doPlus(int scroll) {
		if (isShown() && (scroll + BaBaseApplication.mHeight > locHeight + OFFSET)
				&& (mState == TaskScrollView.UP))
			return true;
		if (isShown() && (scroll < locHeight) && mState == TaskScrollView.DOWN)
			return true;

		return false;
	}

	private boolean doMinus(int scroll) {
		if (isShown() && (scroll > locHeight) && (mState == TaskScrollView.UP))
			return true;

		if (isShown() && (scroll + BaBaseApplication.mHeight - mHeight < locHeight - OFFSET)
				&& (mState == TaskScrollView.DOWN))
			return true;

		return false;
	}

	private Point getRadPoint(Point mrp, float r, float angle) {
		Point point = new Point();
		int x1, y1;
		x1 = (int) (mrp.x + r * Math.cos(Math.toRadians(angle)));
		y1 = (int) (mrp.y + r * Math.sin(Math.toRadians(angle)));
		point.set(x1, y1);
		return point;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 执行完onMeasure后即可获得view的宽度
		mHeight = getMeasuredHeight();
	}

	public int getBarColor() {
		return barColor;
	}

	public void setBarColor(int barColor) {
		this.barColor = barColor;
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);

		if (mViewWidth == 0) {
			mViewWidth = getMeasuredWidth();
		}
	}

	public interface OnclickListener {
		void onClick(int type, View v);
	}

	public OnclickListener getmListener() {
		return mListener;
	}

	public void setmListener(OnclickListener mListener) {
		this.mListener = mListener;
	}

	@Override
	public void onClick(View v) {
		if (null != mListener) {
			mListener.onClick(mNow_Type, v);
		}
	}

}
